import {getUnreadMsgCount} from '~/api/message';
import store from '~/store';

let msgTimer = 0;

export function updateUnreadMsgCount() {
    let loop = true;
    const getter = store.getState();
    if (getter.system.msgNav) {
        const navigation = getter.system.msgNav;
        if (navigation.actions.setParams) {
            if (getter.userinfo.userid > 0) {
                loop = false;
                getUnreadMsgCount().then((res) => {
                    if (res.code === 0) {
                        let count = res.data.count;
                        navigation.setParams({count: count});
                    }
                });
            }
        }
    }
    if (loop) {
        setTimeout(updateUnreadMsgCount, 500);
    }
}

export function checkUnreadMsgCount() {
    if (msgTimer === 0) {
        updateUnreadMsgCount();
        msgTimer = setInterval(updateUnreadMsgCount, 5000);
    }
}

export function resetMsgTimer() {
    if (msgTimer > 0) {
        clearInterval(msgTimer);
        msgTimer = 0;
    }
}
